<template>
  <!-- 生产BOM表单弹窗 -->
  <div>
    <el-dialog
      :close-on-click-modal="false"
      v-model="visibleDialog"
      :title="props.title"
      width="400px"
      draggable
      @close="closeDialog"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :inline="true"
        :rules="rules"
        label-width="160"
        style="width: 400px"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="BOM编号" prop="bomCode" label-width="100px">
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.bomCode"
                placeholder="请输入BOM编号"
                clearable
              />
              <span v-else>{{ formData.bomCode }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              label="BOM描述"
              prop="bomDescription"
              label-width="100px"
            >
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.bomDescription"
                placeholder="请输入BOM描述"
                clearable
              />
              <span v-else>{{ formData.bomDescription }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="工厂" prop="plantId" label-width="100px">
              <el-select
                @change="changePlant"
                v-model="formData.plantId"
                placeholder="请选择工厂"
                style="width: 100%"
                clearable
              >
                <el-option
                  v-for="item in plants"
                  :key="item.id"
                  :label="item.organizationName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              label="成品物料"
              prop="materialId"
              label-width="100px"
            >
              <el-input
                v-model="formData.materialCode"
                placeholder="请选择成品物料"
                :disabled="!formData.plantId"
                clearable
                readonly
                style="width: 77%"
                @click="showWorkOrderSelect"
              >
                <template #append>
                  <el-button
                    type="success"
                    :disabled="!formData.plantId"
                    plain
                    @click="showWorkOrderSelect"
                    >选择</el-button
                  >
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="数量" prop="baseQuantity" label-width="100px">
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.baseQuantity"
                placeholder="请输入数量"
                clearable
              />
              <span v-else>{{ formData.baseQuantity }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              label="数量单位"
              prop="baseQuantityUnit"
              label-width="100px"
            >
              <el-input
                v-model="formData.baseQuantityUnit"
                disabled
                placeholder="请输入数量单位"
                clearable
                :formatter="(data) => useDictionary('MeasurementUnit', data)"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="!props.isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <conten-select
      :visible="selectDialogSELECT.visible"
      @change-visible="changeVisibleSELECT"
      :plantId="formData.plantId"
      :materialType="3"
      :brekList="brekList"
    />
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary";
import { useDictionary } from "@/utils/useTable"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "MESMESBOMEDIT",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  parentId: {
    type: String,
    default: () => {
      return "0";
    },
  },
});

/** 弹窗显示 **/
const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

/** formData定义表单数据 */
const formRef = ref(ElForm);
let formData = reactive({
  id: "",
  bomCode: "",
  bomDescription: "",
  materialId: "",
  materialCode: "",
  parentBomId: "",
  organizationId: "",
  plantId: "",
  plantCode: "",
  plantName: "",
  baseQuantity: "",
  baseQuantityUnit: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: "",
  deleted: "",
});

function validateDegree(rule: any, value: any, callback: (a?: any) => {}) {
  if (isNaN(parseFloat(value)) && isFinite(value)) {
    callback(new Error("请输入整数"));
  } else if (!/^\d{1,9}(\.\d{0,6})?$/.test(value)) {
    callback(new Error("请输入九位整数,六位小数"));
  } else if (Number(value) < 0) {
    callback(new Error("请输入大于0的整数"));
  } else {
    callback();
  }
}
/** rules规则 */
const rules = reactive({
  bomCode: [
    { required: true, message: "请输入BOM编号", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  bomDescription: [
    { required: true, message: "请输入BOM描述", trigger: "blur" },
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  materialId: [
    { required: true, message: "请选择成品物料", trigger: ["blur", "change"] },
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  plantId: [{ required: true, message: "请选择工厂", trigger: "blur" }],
  baseQuantity: [
    { required: true, message: "请输入数量", trigger: "blur" },
    {
      validator: validateDegree,
      trigger: "blur",
    },
  ],
  baseQuantityUnit: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
});

const isValidated = ref(false);
/** 删除行 */
const handleDelete = (index: any) => {
  formData.details.splice(index, 1);
  isValidated.value && formRef.value.validate(() => {});
};

const details = {
  id: "",
  bomId: "",
  componentCode: "",
  materialId: "",
  materialCode: "",
  matQuantity: "",
  quantityUnit: "",
  parentId: "",
  allId: "",
  allCode: "",
  allName: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: "",
  deleted: "",
};

/** 编辑时赋值 */
watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      Object.assign(formData, props.data);
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.bomCode = "";
  formData.bomDescription = "";
  formData.materialId = "";
  formData.materialCode = "";
  formData.parentBomId = "";
  formData.organizationId = "";
  formData.plantId = "";
  formData.plantCode = "";
  formData.plantName = "";
  formData.baseQuantity = "";
  formData.baseQuantityUnit = "";
  formData.version = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = "";
  formData.deleted = "";
}

const loading = ref(false);

/** 生产BOM保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      formData.parentBomId = props.parentId;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/mes/mesbom/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
      isValidated.value = false;
    } else {
      isValidated.value = true;
    }
  });
}

const plants = ref([]);
const getPlants = async () => {
  const data = await request({
    url: "/system/sysOrganization/getList",
    method: "post",
    data: { organizationType: 3 },
  });
  plants.value = data.data;
};
const changePlant = (val) => {
  if (!val) return;
  const find = plants.value.find((item) => item.id === val);
  formData.plantCode = find.organizationCode;
  formData.plantName = find.organizationName;
  formData.materialId = "";
  formData.materialName = "";
  formData.materialCode = "";
  formData.baseQuantityUnit = "";
};

onMounted(() => {
  getPlants();
});

//选择物料弹窗
const selectDialogSELECT = ref({
  visible: false,
});
const changeVisibleSELECT = (val: boolean, data: any) => {
  selectDialogSELECT.value.visible = val;
  if (data) {
    formData.materialId = data.id;
    formData.materialName = data.materialName;
    formData.materialCode = data.materialCode;
    formData.baseQuantityUnit = data.unit;
  }
};
// 回显的数据
const brekList = ref([]);
const showWorkOrderSelect = () => {
  selectDialogSELECT.value.visible = true;
};
</script>
